import VideoPlayer from '../../components/VideoPlayer'
import { Upload } from '@douyinfe/semi-ui'
import { BeforeUploadProps } from '@douyinfe/semi-ui/lib/es/upload/interface'
import { useState, useMemo, useCallback, useContext, useEffect, useRef } from 'react'
import { PlayerControl } from '../../App'
import './style.less'

const VideoList = () => {
  const [videoList, setVideoList] = useState<{ url: string; uid: string; name: string }[]>([])
  const [markers, setMarkers] = useState<{ [name: string]: number[] }>({})
  const { status, voice, grid } = useContext(PlayerControl)

  useEffect(() => {
    document.querySelectorAll('video').forEach(item => {
      status ? item.play() : item.pause()
    })
  }, [status])
  useEffect(() => {
    document.querySelectorAll('video').forEach(item => {
      item.volume = voice
    })
  }, [voice])

  const beforeUpload = ({ file, fileList }: BeforeUploadProps) => {
    const fileInfo = file.name.split('.')
    const fileType = fileInfo.pop()
    const fileName = fileInfo.join('.')

    switch (fileType) {
      case 'mp4':
        if (videoList.length <= 8) {
          setVideoList(videoList => {
            return videoList.concat({ uid: file.uid, name: fileName, url: file.url || '' })
          })
        }
        break
      case 'pbf':
        var reader = new FileReader()
        reader.readAsText(file.fileInstance as Blob, 'UTF-8')
        reader.onload = function (e) {
          let result = e.target?.result
          if (result) {
            const values = (result as string).match(/\d*=\d*\*/g)?.map(item => {
              return Math.floor(parseInt(item.replace(/\d*=(\d*)\*/, '$1')) / 1000)
            })
            values &&
              setMarkers(markers => {
                return {
                  ...markers,
                  [fileName]: values
                }
              })
          }
        }
        break
    }

    return false
  }

  const getMod = () => {
    if (grid) {
      return grid / 33
    } else {
      let len = videoList.length || 1
      if (len >= 3) {
        len -= 1
      }
      return Math.min(len, 3)
    }
  }
  return (
    <div className={`feature-video-list mod-${getMod()}`}>
      {videoList.map((item, index) => {
        return (
          <div className="video-item" key={item.uid}>
            <VideoPlayer src={item.url} markers={markers[item.name] || []}></VideoPlayer>
          </div>
        )
      })}

      {videoList.length <= 9 ? (
        <div className="video-item">
          <Upload
            action="null"
            beforeUpload={beforeUpload}
            draggable={true}
            showUploadList={false}
            accept=".mp4,.pbf"
            dragMainText={'点击上传文件或拖拽文件到这里'}
            dragSubText="支持任意类型文件"
          ></Upload>
        </div>
      ) : null}
    </div>
  )
}

export default VideoList
